//
//  YuFuMoneyView.m
//  NtoccShipper
//
//  Created by mac on 2020/9/30.
//  Copyright © 2020 zhuchongjin. All rights reserved.
//

#import "YuFuMoneyView.h"

 @interface YuFuMoneyView(){
    int timeOld;
    NSTimer * _timer;
    
}
@property (nonatomic,strong) FlexFrameView *frameView;
@property (nonatomic,strong) CJLabel * labTitle;
@property (nonatomic,strong) CJLabel *labAllMoney;
@property (nonatomic,strong) CJLabel *labPayedMoney;
@property (nonatomic,copy) OnSureClick sureBlock;
@property (nonatomic,copy) OnCancleClick cancleBlock;
@property (nonatomic,strong) CJLabel *labYuFuMust; // 必填标识
@property (nonatomic,strong) CJTextField *fieldYuFuMoney; //预付金额

//view
@property (nonatomic,strong) UIView *viewSMSCodeBG;
@property (nonatomic,strong) CJTextField *fieldAouthCode;
@property (nonatomic,strong) CJLabel *labAouthTitle;
@property (nonatomic,strong) FlexTouchView *touchViewGetAouthCode;

@property (strong, nonatomic) CJLabel *labSureTitle;

@property (nonatomic,copy) NSString *strCode;
//@property (nonatomic,copy) NSString *strOrderCode;
//@property (nonatomic,copy) NSString *strOutTradeNo;
//@property (nonatomic,copy) NSString *strOrderNo;
@property (nonatomic,assign) BOOL isNeedSure;  //是否展示确定按钮
@property (nonatomic,strong) CJLabel *labMsgShow;

@property (nonatomic,copy) NSString *strMethod;
@property (nonatomic,copy) NSString *outTradeNo;
@property (nonatomic,copy) NSString *source;
@property (nonatomic,copy) NSString *branchCode;
@property (nonatomic,copy) NSString *payeeType;
@property (nonatomic,copy) NSString *orderNo;
@property (nonatomic,copy) NSString *totalAmount;
@property (nonatomic,copy) NSString *payeeId;
@property (nonatomic,copy) NSString *payerMerchantId;
@property (nonatomic,copy) NSString *body;

@property (nonatomic,strong) FlexTouchView *touchViewSure; // 确认

//                {
//                    method = 6002,
//                    outTradeNo = "20093017243658530000810950027592",
//                    source = "shipment",
//                    branchCode = "27adb23841d547b8ae6f0c11481b4cfd",
//                    payeeType = "MERCHANT",
//                    orderNo = "202009123001540980",
//                    totalAmount = "1100",
//                    payeeId = "226801000000171884120",
//                    payerMerchantId = "226801000000230142625",
//                    body = "运费",
//                }

@end
@implementation YuFuMoneyView

+ (YuFuMoneyView *)shared {
    
    static dispatch_once_t predicate;
    
    static YuFuMoneyView *objc;
    
    dispatch_once(&predicate, ^{
        
        objc = [[YuFuMoneyView alloc] init];
        
    });
    
    return objc;
}

-(instancetype)initWithModel:(SourcesOrderListModel *)model  ClickOnSure:(OnSureClick )sureClick ClickOnCancle:(OnCancleClick )cancleClick{
    
    if (self = [super init]) {
          
        //        self.frame = CGRectMake(0, 0, kScreenWidth - 40, 400);
        //        self.backgroundColor = [UIColor cjWhiteColor];
        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.backgroundColor = [[UIColor cjBlackColor] colorWithAlphaComponent:0.3];

        CGRect rcFrame = CGRectMake(0, 0, kScreenWidth - 40, 0);
       
        if (!self.frameView) {
             self.frameView = [[FlexFrameView alloc] initWithFlex:@"YuFuMoneyView" Frame:rcFrame Owner:self];
        }
        self.frameView.flexibleHeight = YES;

        self.viewSMSCodeBG.hidden = NO;

        [self.frameView layoutIfNeeded];
        [self addSubview:self.frameView];

        self.frameView.center = self.center;
        self.labTitle.font = [UIFont boldSystemFontOfSize:17];
//        self.strOutTradeNo = @"";
//        self.strOrderNo = @"";
        self.strMethod = @"";
        self.strCode = model.code;
        self.isNeedSure = NO;   // 默认是支付
//        self.strOrderCode = model.orderCode;
        
        self.labAllMoney.text = CJStringWithFormat(@"%@元",@(model.taxFee).cj_money_description);
        self.labPayedMoney.text =CJStringWithFormat(@"%@元",@(model.allotTaxAmount).cj_money_description);

        self.outTradeNo = @"";
        self.source = @"";
        self.branchCode = @"";
        self.payeeType = @"";
        self.orderNo = @"";
        self.totalAmount = @"";
        self.payeeId = @"";
        self.payerMerchantId = @"";
        self.body = @"";
        
        self.viewSMSCodeBG.hidden = YES;
        self.labMsgShow.hidden = YES;
        self.labYuFuMust.hidden = NO;
        self.fieldYuFuMoney.enabled = YES;
        self.fieldYuFuMoney.text = @"";
        self.fieldAouthCode.text = @"";
        self.touchViewSure.userInteractionEnabled = YES;
        self.touchViewSure.backgroundColor = [UIColor cjWhiteColor];
        
        self.sureBlock = sureClick;
        self.cancleBlock = cancleClick;
        [self setFieldLimit];
      }

  [self show];
  return self;
}

- (void)setFieldLimit{
    self.fieldYuFuMoney.textFieldType = CJTextFieldStringTypeMoneyValue;
    self.fieldYuFuMoney.maxLength = CJTextLengthTen;
}


#pragma mark ----------获取验证码
- (void)btnTouchViewGetSMSCodeAction{
    DLog(@"获取验证码");
    
    if (self.strMethod.integerValue == 6003) {
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/mybankBalancePay/getVerificationCodeShipperPrepaid",CJBaseUrl);
        NSDictionary *dicPar = @{
             @"orderDetailCode":[CJControl getThreeUnaryValueStr:self.strCode],
             @"totalAmount":[CJControl getThreeUnaryValueStr:self.fieldYuFuMoney.text]
        };

        @weakify(self);
        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PutType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
            
            @strongify(self);
            self.touchViewSure.userInteractionEnabled = YES;
            self.touchViewSure.backgroundColor = [UIColor cjWhiteColor];
            self.touchViewGetAouthCode.userInteractionEnabled = NO;
            timeOld = 60;
            [self startTimer];
    //        self.strOutTradeNo = [CJControl getThreeUnaryValueStr:responseObject[@"outTradeNo"]];
    //        self.strOrderNo = [CJControl getThreeUnaryValueStr:responseObject[@"orderNo"]];
            self.outTradeNo = [CJControl getThreeUnaryValueStr:responseObject[@"outTradeNo"]];
            self.source = [CJControl getThreeUnaryValueStr:responseObject[@"source"]];
            self.branchCode = [CJControl getThreeUnaryValueStr:responseObject[@"branchCode"]];
            self.payeeType = [CJControl getThreeUnaryValueStr:responseObject[@"payeeType"]];
            self.orderNo = [CJControl getThreeUnaryValueStr:responseObject[@"orderNo"]];
            self.totalAmount = [CJControl getThreeUnaryValueStr:responseObject[@"totalAmount"]];
            self.payeeId = [CJControl getThreeUnaryValueStr:responseObject[@"payeeId"]];
            self.payerMerchantId = [CJControl getThreeUnaryValueStr:responseObject[@"payerMerchantId"]];
            self.body = [CJControl getThreeUnaryValueStr:responseObject[@"body"]];
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
        
    }else if(self.strMethod.integerValue == 6004){
       
        if ([CJControl getIsEmpty:self.fieldYuFuMoney.text]) {
            [CJAlert showStringDismissWithDelay:self.fieldYuFuMoney.placeholder];
            return;
        }
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/arpaTransfer/sendVerificationCode",CJBaseUrl);
        NSDictionary *dicPar = @{
            @"phone":[CJControl getLogInPhoneNum],
            @"source":@"shipment", //货主支付/平台支付货主传shipment平台platform
            @"amount":[CJControl getThreeUnaryValueStr:self.fieldYuFuMoney.text]
        };
        
        @weakify(self);
        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
            
            @strongify(self);
            self.touchViewSure.userInteractionEnabled = YES;
            self.touchViewSure.backgroundColor = [UIColor cjWhiteColor];
            self.touchViewGetAouthCode.userInteractionEnabled = NO;
            timeOld = 60;
            [self startTimer];
            self.fieldYuFuMoney.enabled = NO;
            
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
    }
    
    
}

#pragma mark ----------取消
- (void)btnTouchViewClickCancleAction{
    DLog(@"取消");
    [self endEditing:NO];
    [self hidden];
    
}

#pragma mark ----------确定
- (void)btnTouchViewClickSureAction{
    DLog(@"确定");
    [self endEditing:NO];
    
    //        1).status：6001，msg: 本次支付将用平台虚拟余额支付。
    //        2). status：6002，msg: 本次支付将用网商余额支付。
    //data: payerMerchantId, payeeId, payeeType, outTradeNo, totalAmount, body, source, orderNo
    //        3), status：6003，msg: 本次支付将用网商余额支付，请获取验证码。
    //        4), status：6004，msg: 本次支付将用钱包支付。（云企付）

    //页面根据返回状态添加提醒msg
    // 首先判断 用哪种支付
    

    @weakify(self);
    if (self.isNeedSure) {

        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/payAdvance/shipperPrepaidConfirm",CJBaseUrl);
        NSDictionary *dicPar = @{};
//  @{
//            @"code":self.strCode,
//            @"prepaidAmount":[CJControl getThreeUnaryValueStr:self.fieldYuFuMoney.text]
//        };
        
        if (self.strMethod.integerValue == 6001) {
            
            dicPar = @{
                @"code":self.strCode,
                @"prepaidAmount":[CJControl getThreeUnaryValueStr:self.fieldYuFuMoney.text],
                @"operationalCode":self.strMethod
            };
        }else if (self.strMethod.integerValue == 6002 || self.strMethod.integerValue == 6003) {
            
            //                {
            //                    method = 6002,
            //                     = "20093017243658530000810950027592",
            //                     = "shipment",
            //                    branchCode = "27adb23841d547b8ae6f0c11481b4cfd",
            //                     = "MERCHANT",
            //                     = "202009123001540980",
            //                     = "1100",
            //                     = "226801000000171884120",
            //                     = "226801000000230142625",
            //                     = "运费",
            //                }
            
            
            if (self.viewSMSCodeBG.hidden == NO && [CJRegular getIsStrEmpty:self.fieldAouthCode.text]) {
                [CJAlert showStringDismissWithDelay:@"请输入验证码"];
                return;
            }
            
            dicPar = @{
                @"code":self.strCode,
                @"prepaidAmount":[CJControl getThreeUnaryValueStr:self.fieldYuFuMoney.text],
                @"operationalCode":self.strMethod,
                @"outTradeNo":self.outTradeNo,
                @"source":self.source,
                @"payeeType":self.payeeType,
                @"orderNo":self.orderNo,
                @"totalAmount":self.totalAmount,
                @"payeeId":self.payeeId,
                @"payerMerchantId":self.payerMerchantId,
                @"body":self.body,
                @"verificationCode":[CJControl getThreeUnaryValueStr:self.fieldAouthCode.text]
            };
            
        }else if (self.strMethod.integerValue == 6004){
            
            if (self.viewSMSCodeBG.hidden == NO && [CJRegular getIsStrEmpty:self.fieldAouthCode.text]) {
                [CJAlert showStringDismissWithDelay:@"请输入验证码"];
                return;
            }
            
            dicPar = @{
                        @"code":self.strCode,
                        @"prepaidAmount":self.fieldYuFuMoney.text, //预付金额（元）
                        @"operationalCode":self.strMethod,//支付方式
                        @"verificationCode":self.viewSMSCodeBG.hidden ? @"":self.fieldAouthCode.text, // 验证码
                    };
        }

        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
            
            @strongify(self);
            if (self.sureBlock) {
                self.sureBlock(@"");
            }
            [self hidden];

        } failure:^(NSError * _Nonnull error) {
            
        }];

    }else{
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/payAdvance/shipperPrepaid",CJBaseUrl);
        NSDictionary *dicPar = @{
            @"code":self.strCode,
            @"prepaidAmount":[CJControl getThreeUnaryValueStr:self.fieldYuFuMoney.text]
        };

        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dicPar status:ArpaDefault success:^(id  _Nonnull responseObject) {
            
            //        1).status：6001，msg: 本次支付将用平台虚拟余额支付。中台
            //        2). status：6002，msg: 本次支付将用网商余额支付。
            //data: payerMerchantId, payeeId, payeeType, outTradeNo, totalAmount, body, source, orderNo
            //        3), status：6003，msg: 本次支付将用网商余额支付，请获取验证码。
            //                    4), status：6004，msg: 本次支付将用钱包支付。（云企付）
            //页面根据返回状态添加提醒msg
            NSString *method = responseObject[@"method"];
            self.isNeedSure = YES;
            self.labSureTitle.text = @"确认";
            self.fieldYuFuMoney.enabled = NO;
            self.labYuFuMust.hidden = YES;
            self.strMethod = method;
            self.viewSMSCodeBG.hidden = YES;
            self.labMsgShow.hidden = NO;
            self.labMsgShow.text = [CJControl getThreeUnaryValueStr:responseObject[@"message"]];
            
            if (method.integerValue == 6001) {
                
            }else if (method.integerValue == 6002){
                
        //                {
        //                    method = 6002,
        //                    outTradeNo = "20093017243658530000810950027592",
        //                    source = "shipment",
        //                    branchCode = "27adb23841d547b8ae6f0c11481b4cfd",
        //                    payeeType = "MERCHANT",
        //                    orderNo = "202009123001540980",
        //                    totalAmount = "1100",
        //                    payeeId = "226801000000171884120",
        //                    payerMerchantId = "226801000000230142625",
        //                    body = "运费",
        //                }

                self.outTradeNo = [CJControl getThreeUnaryValueStr:responseObject[@"outTradeNo"]];
                self.source = [CJControl getThreeUnaryValueStr:responseObject[@"source"]];
                self.branchCode = [CJControl getThreeUnaryValueStr:responseObject[@"branchCode"]];
                self.payeeType = [CJControl getThreeUnaryValueStr:responseObject[@"payeeType"]];
                self.orderNo = [CJControl getThreeUnaryValueStr:responseObject[@"orderNo"]];
                self.totalAmount = [CJControl getThreeUnaryValueStr:responseObject[@"totalAmount"]];
                self.payeeId = [CJControl getThreeUnaryValueStr:responseObject[@"payeeId"]];
                self.payerMerchantId = [CJControl getThreeUnaryValueStr:responseObject[@"payerMerchantId"]];
                self.body = [CJControl getThreeUnaryValueStr:responseObject[@"body"]];

            }else if (method.integerValue == 6003){
                self.viewSMSCodeBG.hidden = NO;
        //                [self.frameView layoutIfNeeded];
                self.touchViewSure.userInteractionEnabled = NO;
                self.touchViewSure.backgroundColor = [UIColor cjLineBackGroundColor];
            }else if (method.integerValue == 6004){
        //
        //                    {
        //                        "msg": "本次支付将用钱包支付。",
        //                        "method": 6004,
        //                        "data": {
        //                            "method": 6004,
        //                            "message": "本次支付将用钱包支付。",
        //                            "needSmsCode": "no"
        //                        },
        //                        "status": 0
        //                    }
                
                if ([[CJControl getThreeUnaryValueStr:responseObject[@"needSmsCode"]] isEqualToString:@"no"]) {
                    
                }else{
                    self.viewSMSCodeBG.hidden = NO;
        //                [self.frameView layoutIfNeeded];
                    self.touchViewSure.userInteractionEnabled = NO;
                    self.touchViewSure.backgroundColor = [UIColor cjLineBackGroundColor];
                }
                
            }
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
    }

}


- (void)startTimer{
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireOdlM) userInfo:nil repeats:YES];
}

- (void)stopTimer{
    
    if (_timer == nil) {
        return;
    }
    [_timer invalidate];
    _timer = nil;
}

- (void)dealloc{
    
   NSLog(@"%s",__func__);
    [_timer invalidate];
    _timer = nil;
}

- (void)timerFireOdlM{
    
    NSString * str =[NSString stringWithFormat:@"%ds",timeOld];
    self.labAouthTitle.text = str;
    timeOld--;
    if (timeOld==0) {
        [self stopTimer];
        timeOld=60;
        self.labAouthTitle.text = @"获取验证码";
        self.touchViewGetAouthCode.userInteractionEnabled = YES;
        
    }
}



/// 展示隐藏
- (void)show {
    [[UIApplication sharedApplication].keyWindow addSubview:self];
//    _titleLabel.text = _title;
//    _msgLabel.text = _message;
    self.center = [UIApplication sharedApplication].keyWindow.center;
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 1.0;
    }];
}

- (void)hidden {
    
    @weakify(self);
    [UIView animateWithDuration:0.5 animations:^{
        
        @strongify(self);
        self.alpha = 0.0;
        self.labAouthTitle.text = @"获取验证码";
        [self stopTimer];
        timeOld=60;
        self.touchViewGetAouthCode.userInteractionEnabled = YES;
    }];
}
@end

